package com.lkk.cg.util;

import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;

/**
 * Created by lkk on 2014/12/21.
 */
public class FileExtensionValidator extends FieldValidatorSupport {

    private String allowedExtensions;

    public String getAllowedExtensions() {
        return allowedExtensions;
    }

    public void setAllowedExtensions(String allowedExtensions) {
        this.allowedExtensions = allowedExtensions;
    }

    public void validate(Object object) throws ValidationException {
        String fieldName = getFieldName();
        Object val = getFieldValue(fieldName + "FileName", object);
        if (val != null) {
            String ext = FileUtils.getFileNameExtension((String) val);
            String[] allowed = StringUtils.split(allowedExtensions, ',');
            if (!Arrays.asList(allowed).contains(ext.toLowerCase()))
                addFieldError(getFieldName(), object);
        }
    }

}
